package com.ucpaas.sms.service.componentConf;

import com.jsmsframework.common.constant.SysConstant;
import com.jsmsframework.common.enums.middleware.ModeType;
import com.jsmsframework.common.util.BeanUtil;
import com.jsmsframework.common.util.JsonUtil;
import com.jsmsframework.middleware.dto.ComponentRefMqDTO;
import com.jsmsframework.middleware.entity.JsmsComponentRefMq;
import com.jsmsframework.middleware.exception.JsmsComponentRefMqException;
import com.jsmsframework.middleware.service.JsmsComponentRefMqService;
import com.ucpaas.sms.constant.LogConstant;
import com.ucpaas.sms.dao.MessageMasterDao;
import com.ucpaas.sms.enums.LogEnum;
import com.ucpaas.sms.model.PageContainer;
import com.ucpaas.sms.service.LogService;
import com.ucpaas.sms.util.web.AuthorityUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class MqRelation5point17point11ServiceImpl implements MqRelationService {

	private static final Logger LOGGER = LoggerFactory.getLogger(MqConfigServiceImpl.class);
	
	@Autowired
	private MessageMasterDao messageMasterDao;

	@Autowired
	private JsmsComponentRefMqService jsmsComponentRefMqService;

	@Autowired
	private LogService logService;


	@Override
	public PageContainer query(Map<String, String> params) {
		return messageMasterDao.getSearchPage("mqRelation.query", "mqRelation.queryCount", params);
	}

	@Override
	public Map<String, Object> editView(int id) {
		return messageMasterDao.getOneInfo("mqRelation.getOneInfo", id);
	//	return jsmsComponentRefMqService.getById(id);
	}


	@Override
	public Map<String, Object> editView(Integer componentId,String messageType,Integer mode) {
		//return messageMasterDao.getOneInfo("mqRelation.getOneInfo", id);
		ComponentRefMqDTO dto= jsmsComponentRefMqService.queryByCMM(componentId,messageType,mode);

		return BeanUtil.beanToMap(dto,false);
	}

	@Override
	public Map<String, Object> update(Map<String, String> params) {
		Map<String, Object> data = new HashMap<String, Object>();
		int saveNum;
		String id = Objects.toString(params.get("id"), "");
		
		if(StringUtils.isBlank(id)){// 新建
			saveNum = messageMasterDao.insert("mqRelation.insert", params);
			id = String.valueOf(params.get("id")); // 获得mybatis返回的插入数据的主键ID
		}else{// 更新
			saveNum = messageMasterDao.update("mqRelation.update", params);
		}
		
		if(saveNum == 1){
			data.put("result", "success");
			data.put("id", id);
			data.put("msg", "保存成功");
			return data;
		}else{
			data.put("result", "success");
			data.put("msg", "保存失败");
			return data;
		}
	}

	@Override
	public Map<String, Object> delete(Map<String, String> params) {
		Map<String, Object> result = new HashMap<String, Object>();
		int delNum = messageMasterDao.delete("mqRelation.delete", params);
		if(delNum == 1){
			result.put("result", "success");
			result.put("msg", "成功删除记录");
			logService.add(LogConstant.LogType.delete, LogEnum.组件配置.getValue(),"组件配置-SMSP组件与MQ关联配置：删除SMSP组件与MQ关联成功","删除数据："+JsonUtil.toJson(params),"当前成功:"+JsonUtil.toJson(params),"操作人："+ AuthorityUtils.getLoginRealName());
		}else{
			result.put("result", "fail");
			result.put("msg", "删除记录失败");
			logService.add(LogConstant.LogType.delete, LogEnum.组件配置.getValue(),"组件配置-SMSP组件与MQ关联配置：删除SMSP组件与MQ关联失败","删除数据："+JsonUtil.toJson(params),"当前失败:"+JsonUtil.toJson(params),"操作人："+ AuthorityUtils.getLoginRealName());
			throw  new JsmsComponentRefMqException("编辑时删除记录失败,数据为="+JsonUtil.toJson(params));
		}
		return result;
	}

	@Override
	public List<Map<String, Object>> queryAllMqQueue(Map<String, String> params) {
		return messageMasterDao.getSearchList("mqRelation.queryAllMqQueue", params);
	}

	@Override
	@Transactional
	public Map<String, Object> create(Map<String, String> params) {
		Map<String, Object> result = new HashMap<String, Object>();
		String componentId = params.get("componentId");
		String messageType=params.get("messageType");
		Integer mode=Integer.valueOf(params.get("mode"));
		String ids=params.get("ids");
		JsmsComponentRefMq ref=new JsmsComponentRefMq();
		ref.setComponentId(Integer.valueOf(componentId).intValue());
		ref.setMessageType(messageType);
		ref.setRemark(params.get("remark"));
		String [] mqIdArray = params.get("mqIdAndOther").split(",");
		if(Objects.equals(mode, ModeType.生产者.getValue())){
			for (int i = 0; i < mqIdArray.length; i++) {
				String[]  mq=mqIdArray[i].split("\\|");
				// 传值：mqId|weight|id
				if(mq.length==3){

					ref.setMode(ModeType.生产者.getValue());
					ref.setMqId(Integer.valueOf(mq[0]).intValue());
					ref.setWeight(Integer.valueOf(mq[1]).intValue());
					ref.setUpdateDate(new Date());

					String id=mq[2];
					if(!NumberUtils.isNumber(id)){
						result.put("result", SysConstant.FAIL);
						result.put("msg", "保存失败,参数非法！");
						LOGGER.error("写入Mq和SMSP组件生产者关系时失败,参数非法！");
						throw  new JsmsComponentRefMqException("写入Mq和SMSP组件生产者关系时失败,关系为data"+ JsonUtil.toJson(ref));

					}else {
						int idInt=Integer.valueOf(id).intValue();
						if(Objects.equals(idInt,-1)){
							// -1表示新增
							int add=jsmsComponentRefMqService.insert(ref);
							if(add>0){
								result.put("result", SysConstant.SUCCESS);
								result.put("msg", "保存成功");
								logService.add(ids==null?LogConstant.LogType.add:LogConstant.LogType.update, LogEnum.组件配置.getValue(),"组件配置-SMSP组件与MQ关联配置：添加SMSP组件与MQ关联成功","添加数据："+JsonUtil.toJson(params),"当前成功:"+JsonUtil.toJson(ref),"操作人："+ AuthorityUtils.getLoginRealName());
							}else {
								result.put("result", SysConstant.FAIL);
								result.put("msg", "保存失败");
								LOGGER.error("写入Mq和SMSP组件生产者关系时失败");
								logService.add(ids==null?LogConstant.LogType.add:LogConstant.LogType.update, LogEnum.组件配置.getValue(),"组件配置-SMSP组件与MQ关联配置：添加SMSP组件与MQ关联失败","添加数据："+JsonUtil.toJson(params),"当前操作失败:"+JsonUtil.toJson(ref),"操作人："+ AuthorityUtils.getLoginRealName());
								throw  new JsmsComponentRefMqException("写入Mq和SMSP组件生产者关系时失败,关系为data"+ JsonUtil.toJson(ref));
							}



						}else {
							JsmsComponentRefMq checkRef=jsmsComponentRefMqService.getById(idInt);
							if(checkRef==null){
								result.put("result", SysConstant.FAIL);
								result.put("msg", "更新Mq和SMSP组件生产者关系失败,原配置ID="+idInt+"不存在！");
								LOGGER.error("更新Mq和SMSP组件生产者关系失败,原配置ID={}不存在！",idInt);
								throw  new JsmsComponentRefMqException("写入Mq和SMSP组件生产者关系时失败,关系为data"+ JsonUtil.toJson(ref));
							}else {
								checkRef.setUpdateDate(new Date());
								checkRef.setWeight(Integer.valueOf(mq[1]).intValue());
								checkRef.setMqId(Integer.valueOf(mq[0]).intValue());
								checkRef.setRemark(params.get("remark"));

								int up=jsmsComponentRefMqService.update(checkRef);

								if(up>0){
									result.put("result", SysConstant.SUCCESS);
									result.put("msg", "保存成功");
									logService.add(LogConstant.LogType.update, LogEnum.组件配置.getValue(),"组件配置-SMSP组件与MQ关联配置：修改SMSP组件与MQ关联成功","修改数据："+JsonUtil.toJson(params),"当前成功:"+JsonUtil.toJson(ref),"操作人："+ AuthorityUtils.getLoginRealName());
								}else {
									result.put("result", SysConstant.FAIL);
									result.put("msg", "保存失败");
									LOGGER.error("写入Mq和SMSP组件生产者关系时失败");
									logService.add(LogConstant.LogType.update, LogEnum.组件配置.getValue(),"组件配置-SMSP组件与MQ关联配置：修改SMSP组件与MQ关联失败","修改数据："+JsonUtil.toJson(params),"当前操作失败:"+JsonUtil.toJson(ref),"操作人："+ AuthorityUtils.getLoginRealName());
									throw  new JsmsComponentRefMqException("写入Mq和SMSP组件生产者关系时失败,关系为data"+ JsonUtil.toJson(ref));
								}
							}


						}


					}



				}else {
					result.put("result", SysConstant.FAIL);
					result.put("msg", "保存失败,参数非法！");
					LOGGER.error("写入Mq和SMSP组件生产者关系时失败,参数非法！");
					throw  new JsmsComponentRefMqException("写入Mq和SMSP组件生产者关系时失败,关系为data"+ JsonUtil.toJson(ref));
				}




			}



		}
		if(Objects.equals(mode,ModeType.消费者.getValue())){
			for (int i = 0; i < mqIdArray.length; i++) {
				String[]  mq=mqIdArray[i].split("\\|");
				// 传值：mqId|weight|id
				if(mq.length==3){

					ref.setMode(ModeType.消费者.getValue());
					ref.setMqId(Integer.valueOf(mq[0]).intValue());
					ref.setGetRate(Integer.valueOf(mq[1]).intValue());
					ref.setUpdateDate(new Date());

					String id=mq[2];
					if(!NumberUtils.isNumber(id)){
						result.put("result", SysConstant.FAIL);
						result.put("msg", "保存失败,参数非法！");
						LOGGER.error("写入Mq和SMSP组件消费者关系时失败,参数非法！");
						throw  new JsmsComponentRefMqException("写入Mq和SMSP组件消费者关系时失败,关系为data"+ JsonUtil.toJson(ref));

					}else {
						int idInt=Integer.valueOf(id).intValue();
						if(Objects.equals(idInt,-1)){
							// -1表示新增
							int add=jsmsComponentRefMqService.insert(ref);
							if(add>0){
								result.put("result", SysConstant.SUCCESS);
								result.put("msg", "保存成功");
								logService.add(ids==null?LogConstant.LogType.add:LogConstant.LogType.update, LogEnum.组件配置.getValue(),"组件配置-SMSP组件与MQ关联配置：添加SMSP组件与MQ关联成功","添加数据："+JsonUtil.toJson(params),"当前成功:"+JsonUtil.toJson(ref),"操作人："+ AuthorityUtils.getLoginRealName());
							}else {
								result.put("result", SysConstant.FAIL);
								result.put("msg", "保存失败");
								LOGGER.error("写入Mq和SMSP组件生产者关系时失败");
								logService.add(ids==null?LogConstant.LogType.add:LogConstant.LogType.update, LogEnum.组件配置.getValue(),"组件配置-SMSP组件与MQ关联配置：添加SMSP组件与MQ关联失败","添加数据："+JsonUtil.toJson(params),"当前操作失败:"+JsonUtil.toJson(ref),"操作人："+ AuthorityUtils.getLoginRealName());
								throw  new JsmsComponentRefMqException("写入Mq和SMSP组件消费者关系时失败,关系为data"+ JsonUtil.toJson(ref));
							}

						}else {
							JsmsComponentRefMq checkRef=jsmsComponentRefMqService.getById(idInt);
							if(checkRef==null){
								result.put("result", SysConstant.FAIL);
								result.put("msg", "更新Mq和SMSP组件消费者关系失败,原配置ID="+idInt+"不存在！");
								LOGGER.error("更新Mq和SMSP组件消费者关系失败,原配置ID={}不存在！",idInt);
								throw  new JsmsComponentRefMqException("写入Mq和SMSP组件消费者关系时失败,关系为data"+ JsonUtil.toJson(ref));
							}else {
								checkRef.setUpdateDate(new Date());
								checkRef.setGetRate(Integer.valueOf(mq[1]).intValue());
								checkRef.setMqId(Integer.valueOf(mq[0]).intValue());
								checkRef.setRemark(params.get("remark"));


								int up=jsmsComponentRefMqService.update(checkRef);

								if(up>0){
									result.put("result", SysConstant.SUCCESS);
									result.put("msg", "保存成功");
									logService.add(LogConstant.LogType.update, LogEnum.组件配置.getValue(),"组件配置-SMSP组件与MQ关联配置：修改SMSP组件与MQ关联成功","修改数据："+JsonUtil.toJson(params),"当前成功:"+JsonUtil.toJson(ref),"操作人："+ AuthorityUtils.getLoginRealName());
								}else {
									result.put("result", SysConstant.FAIL);
									result.put("msg", "保存失败");
									LOGGER.error("写入Mq和SMSP组件消费者关系时失败");
									logService.add(LogConstant.LogType.update, LogEnum.组件配置.getValue(),"组件配置-SMSP组件与MQ关联配置：修改SMSP组件与MQ关联失败","修改数据："+JsonUtil.toJson(params),"当前操作失败:"+JsonUtil.toJson(ref),"操作人："+ AuthorityUtils.getLoginRealName());
									throw  new JsmsComponentRefMqException("写入Mq和SMSP组件消费者关系时失败,关系为data"+ JsonUtil.toJson(ref));
								}
							}


						}

					}

				}else {
					result.put("result", SysConstant.FAIL);
					result.put("msg", "保存失败,参数非法！");
					LOGGER.error("写入Mq和SMSP组件消费者关系时失败,参数非法！");
					throw  new JsmsComponentRefMqException("写入Mq和SMSP组件消费者关系时失败,关系为data"+ JsonUtil.toJson(ref));
				}


		}

		}

		return result;
	}


	/*@Override
	public Map<String, Object> create(Map<String, String> params) {
		Map<String, Object> result = new HashMap<String, Object>();
		String componentId = params.get("componentId");
		String messageType=params.get("messageType");
		Integer mode=Integer.valueOf(params.get("mode"));
		String ids=params.get("ids");
		if(StringUtils.isNotBlank(ids)){
			//修改，先删后加
			String[] ids1=ids.split(",");

			for (String s : ids1) {
				Map<String ,String> delparam=new HashedMap();
				delparam.put("id",s);
				result=this.delete(delparam);
				if(Objects.equals(result.get("result"),SysConstant.FAIL)){
					return  result;
				}
			}
			
			
		}
		JsmsComponentRefMq ref=new JsmsComponentRefMq();
		ref.setComponentId(Integer.valueOf(componentId).intValue());
		ref.setMessageType(messageType);
		ref.setRemark(params.get("remark"));
		String [] mqIdArray = params.get("mqIdAndOther").split(",");
		if(Objects.equals(mode, ModeType.生产者.getValue())){
			for (int i = 0; i < mqIdArray.length; i++) {
				String[]  mq=mqIdArray[i].split("\\|");


				ref.setMode(ModeType.生产者.getValue());
				ref.setMqId(Integer.valueOf(mq[0]).intValue());
				ref.setWeight(Integer.valueOf(mq[1]).intValue());
				ref.setUpdateDate(new Date());

				int add=jsmsComponentRefMqService.insert(ref);
				if(add>0){
					result.put("result", SysConstant.SUCCESS);
					result.put("msg", "保存成功");
					logService.add(ids==null?LogConstant.LogType.add:LogConstant.LogType.update, LogEnum.组件配置.getValue(),"组件配置-SMSP组件与MQ关联配置：添加SMSP组件与MQ关联成功","添加数据："+JsonUtil.toJson(params),"当前成功:"+JsonUtil.toJson(ref),"操作人："+ AuthorityUtils.getLoginRealName());
				}else {
					result.put("result", SysConstant.FAIL);
					result.put("msg", "保存失败");
					LOGGER.error("写入Mq和SMSP组件生产者关系时失败");
					logService.add(ids==null?LogConstant.LogType.add:LogConstant.LogType.update, LogEnum.组件配置.getValue(),"组件配置-SMSP组件与MQ关联配置：添加SMSP组件与MQ关联失败","添加数据："+JsonUtil.toJson(params),"当前操作失败:"+JsonUtil.toJson(ref),"操作人："+ AuthorityUtils.getLoginRealName());
					throw  new JsmsComponentRefMqException("写入Mq和SMSP组件生产者关系时失败,关系为data"+ JsonUtil.toJson(ref));
				}


			}



		}
		if(Objects.equals(mode,ModeType.消费者.getValue())){
			for (int i = 0; i < mqIdArray.length; i++) {
				String[]  mq=mqIdArray[i].split("\\|");
				ref.setMode(ModeType.消费者.getValue());
				ref.setMqId(Integer.valueOf(mq[0]).intValue());
				ref.setGetRate(Integer.valueOf(mq[1]).intValue());
				ref.setUpdateDate(new Date());
				int add=jsmsComponentRefMqService.insert(ref);
				if(add>0){
					result.put("result", SysConstant.SUCCESS);
					result.put("msg", "保存成功");
					logService.add(LogConstant.LogType.add, LogEnum.组件配置.getValue(),"组件配置-SMSP组件与MQ关联配置：添加SMSP组件与MQ关联成功","添加数据："+JsonUtil.toJson(params),"当前成功:"+JsonUtil.toJson(ref),"操作人："+ AuthorityUtils.getLoginRealName());
				}else {
					result.put("result", SysConstant.FAIL);
					result.put("msg", "保存失败");
					LOGGER.error("写入Mq和SMSP组件消费者关系时失败");
					logService.add(LogConstant.LogType.add, LogEnum.组件配置.getValue(),"组件配置-SMSP组件与MQ关联配置：添加SMSP组件与MQ关联失败","添加数据："+JsonUtil.toJson(params),"当前操作失败:"+JsonUtil.toJson(ref),"操作人："+ AuthorityUtils.getLoginRealName());
					throw  new JsmsComponentRefMqException("写入Mq和SMSP组件消费者关系时失败,关系为data"+ JsonUtil.toJson(ref));
				}
			}


		}

		return result;
	}*/
	
	private boolean insertMqRelationInfo(List<String> mqIdList, String mqMode, String componentId){
		List<Map<String, Object>> insertList = new ArrayList<Map<String, Object>>();
		
		String get_rate;
		if(mqMode.equals("1")){
			get_rate = "50";
		}else{
			get_rate = "0";
		}
		
		Map<String, Object> sqlParams = new HashMap<String, Object>();
		sqlParams.put("componentId", componentId);
		for (String mqId : mqIdList) {
			sqlParams.put("mqId", mqId);
			sqlParams.put("mqMode", mqMode);
			int mqAndCompenontRelationNum = messageMasterDao.getSearchSize("mqRelation.queryMqAndCompenontRelationNum", sqlParams);
			if(mqAndCompenontRelationNum > 0){
				continue;
			}
			Map<String, Object> mqRalationSaveInfo = new HashMap<String, Object>();
			Map<String, Object> mqInfo = messageMasterDao.getOneInfo("mqRelation.getMqInfoById", mqId);
			mqRalationSaveInfo.put("component_id", componentId);
			mqRalationSaveInfo.put("message_type", mqInfo.get("message_type"));
			mqRalationSaveInfo.put("mode", mqMode);
			mqRalationSaveInfo.put("mq_id", mqId);
			mqRalationSaveInfo.put("get_rate", get_rate);
			insertList.add(mqRalationSaveInfo);
		}
		
		if(insertList.size() > 0){
			try {
				sqlParams = new HashMap<String, Object>();
				sqlParams.put("insertList", insertList);
				messageMasterDao.insert("mqRelation.insertMqRelationList", sqlParams);
			} catch (Exception e) {
				LOGGER.error("写入Mq和SMSP组件关系时系统错误：" + e);
				return false;
			}
		}
		return true;
	}

	@Override
	public Map<String, Object> updateMqGetRate(Map<String, String> params) {
		Map<String, Object> result = new HashMap<String, Object>();
		int num = messageMasterDao.update("mqRelation.updateMqGetRate", params);
		if(num > 0){
			result.put("result", "success");
			result.put("msg", "保存成功");
		}else{
			result.put("result", "fail");
			result.put("msg", "保存失败");
		}
		return result;
	}

}
